<template>
  <div class="table-wrapper">
    <el-table
      v-loading="loading"
      :data="dataList"
      :height="height !== 0 ? height : null"
      :max-height="maxHeight"
      :cell-class-name="cellClassName"
      stripe
      border
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick">
      <slot name="left" />
      <template v-for="(item, index) in fieldList">
        <el-table-column
          v-if="item.formType === 'pic'"
          :key="index"
          :label="item.name"
          :fixed="item.fixed"
          :prop="item.fieldName"
          width="112"
          header-align="left"
          align="center">
          <template slot-scope="scope">
            <template
              v-if="scope.row[scope.column.property] instanceof Array">
              <adapter-image
                v-for="(valObj, valIndex) in scope.row[scope.column.property]"
                :key="valIndex"
                :src="valObj.url"
                @click.stop="previewImage(scope, valIndex)" />
            </template>
            <template v-else>
              <adapter-image
                :src="scope.row[scope.column.property]"
                @click.stop="previewImage(scope, null)" />
            </template>
          </template>
        </el-table-column>
        <el-table-column
          v-else-if="!item.isHide"
          :key="index"
          :fixed="item.fixed"
          :prop="item.fieldName"
          :label="item.name"
          :width="item.width || ''"
          :min-width="100"
          :sortable="item.sortable || false"
          :class-name="item.canVisit ? 'can-visit--underline' : ''"
          :formatter="item.formatter || null"
          show-overflow-tooltip />
      </template>
      <el-table-column v-if="dataList.length === 0" />
      <slot name="right" />
    </el-table>

    <div
      v-if="showPage"
      class="p-contianer">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size.sync="pageSize"
        :total="total"
        :pager-count="5"
        class="p-bar"
        background
        layout="prev, pager, next, sizes, total, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
  </div>
</template>

<script>
import TableMixin from '../../mixins/Table'
import { objDeepCopy } from '@/utils'
import { isEmpty, isObject } from '@/utils/types'
import { separator } from '@/filters/vueNumeralFilter/filters'

export default {
  name: 'TabTable',
  mixins: [TableMixin],
  props: {
    /**
     * 请求配置
     * {
     *   fieldRequest: Function 表头字段请求
     *   fieldParams: Object 表头字段请求参数
     *   fieldList: Array 表头字段列表（如果有值则不会再去发起表头字段请求）
     *   listRequest: Function 列表数据请求
     *   listParams: Object 列表数据请求参数
     *   list: Array 列表数据（如果有值则不会再发起列表请求）
     *   canVisitField: String[] 可点击的字段
     * }
     */
    requestConfig: {
      type: Object,
      required: true
    },
    height: { // 表格高度
      type: Number,
      default: 350
    },
    maxHeight: {
      type: Number,
      default: null
    },
    showPage: { // 是否使用分页器
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      canResizeTable: false,

      dataList: [],
      fieldList: []
    }
  },
  watch: {
    requestConfig: {
      handler() {
        this.getFieldList()
      },
      deep: true
    }
  },
  created() {
    this.getFieldList()
  },
  methods: {
    // 重写mixins中的方法
    getDataList() {},

    getFieldList() {
      if (this.requestConfig.fieldList) {
        this.fieldList = objDeepCopy(this.requestConfig.fieldList)
        this.getFormatter()
        this.getListData()
      } else {
        const request = this.requestConfig.fieldRequest
        const params = this.requestConfig.fieldParams || {}
        if (!request) return
        this.loading = true
        request(params).then(res => {
          this.loading = false
          console.log('getFieldList res: ', res.data)
          this.fieldList = res.data
          this.getFormatter()
          this.getListData()
        }).catch(() => {
          this.loading = false
        })
      }
    },

    getFormatter() {
      const canVisitField = this.requestConfig.canVisitField || null
      this.fieldList.forEach(item => {
        if (canVisitField && canVisitField.includes(item.fieldName)) {
          item.fixed = 'left'
          item.canVisit = true
        }
        if (item.formType === 'pic') {
          item.fixed = 'left'
        }
        if (!item.formatter) {
          if ([
            'supplier_cause',
            'purchase_cause',
            'sale_cause',
            'salereturn_cause',
            'retreat_cause'
          ].includes(item.formType)) {
            item.formatter = function(row, column, cellValue, index) {
              if (!isEmpty(cellValue)) {
                return cellValue.name
              }
              return '--'
            }
          } else if (item.formType === 'floatnumber') {
            item.formatter = function(row, column, cellValue, index) {
              return separator(cellValue || 0)
            }
          } else {
            item.formatter = function(row, column, cellValue, index) {
              if (isObject(cellValue)) {
                return cellValue.name || cellValue || '--'
              }
              return isEmpty(cellValue) ? '--' : cellValue
            }
          }
        }
      })
    },

    getListData() {
      if (this.requestConfig.list) {
        this.dataList = this.requestConfig.list
      } else {
        const request = this.requestConfig.listRequest
        const params = this.requestConfig.listParams || null
        if (!request) return
        this.loading = true
        request(params).then(res => {
          this.loading = false
          // console.log('getDataList res: ', res.data)
          const list = res.data.hasOwnProperty('list') ? res.data.list : res.data
          this.dataList = list instanceof Array ? list : []
          this.$emit('render-ok', {
            fieldList: this.fieldList,
            data: this.dataList
          })
        }).catch(() => {
          this.loading = false
        })
      }
    },

    getUrl(val) {
      if (!val) return ''
      if (Object.prototype.toString.call(val) === '[object Array]') {
        if (val.length > 0) return val[0]
        return ''
      } else {
        return val
      }
    },

    previewImage(scope, dataIndex = null) {
      let arr = []
      const field = scope.column.property
      if (isEmpty(scope.row[field])) return
      const nowUrl = dataIndex === null ? scope.row[field].url : scope.row[field][dataIndex].url
      this.dataList.forEach((item, i) => {
        if (item[field] instanceof Array) {
          arr = arr.concat(item[field])
        } else {
          arr.push(item[field])
        }
      })
      arr = arr.filter(o => !!o)
      const findIndex = arr.findIndex(o => o.url === nowUrl)
      this.$bus.emit('preview-image-bus', {
        index: findIndex,
        data: arr
      })
    },

    /**
     * 表格行点击
     * @param row
     * @param column
     */
    handleRowClick(row, column) {
      if (column.type === 'selection') {
        return // 多选布局不能点击
      }
      if (this.canVisitFields.includes(column.property)) {
        this.$emit('row-click', row, column.property)
      }
    },
    handleSelectionChange(data) {
      this.$emit('selection-change', data)
    },

    /**
     * 调整每页显示的数据条数
     * @param size
     */
    handleSizeChange(size) {
      this.pageSize = size
      this.$emit('list', {
        page: this.currentPage,
        limit: this.pageSize
      })
    },

    /**
     * 翻页
     * @param page
     */
    handleCurrentChange(page) {
      this.currentPage = page
      this.$emit('list', {
        page: this.currentPage,
        limit: this.pageSize
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .el-table {
    border-bottom: 1px solid $xr-border-color-base;
  }
  .p-contianer {
    border-top: 0 none;
  }

  // /deep/ .el-table__body .el-table__row td:first-child .cell {
  //  padding-left: 10px !important;
  // }
  .product-pic {
    max-width: 80px;
    max-height: 100px;
    vertical-align: middle;
    margin: 8px auto;
  }
</style>
